import Koa from "koa";
import KoaRouter from "koa-router";
import { DataSource, DataSourceOptions } from "typeorm";
import { Container } from "@/common/core/index";
import { KoaContext, KoaNext } from "@/types/index";
import { extractLikeValue } from "../util";

export class MyApplication {
  private app = new Koa();
  public dataSource!: DataSource;
  public container = new Container();
  protected prefix: string = "";

  setup(modules: any[]) {
    Object.values(modules).forEach((module: Function) => {
      this.container.initLoad(module);
    });

    this.createRouter();
  }

  createRouter() {
    const router: any = new KoaRouter({ prefix: this.prefix });
    this.container.getRouter().forEach((item: any) => {
      router[item.requestMethod](item.prefix + item.path, async (ctx: KoaContext, next: KoaNext) => {
        await this.container.registerService(item.uuid);
        const inst = await this.container.getInstance(item.uuid);

        Object.defineProperty(inst, "ctx", {
          value: ctx,
          writable: false,
          enumerable: false,
        });
        const response = await extractLikeValue(ctx, item.requestData);
        // console.log("getRouteData", item);
        ctx.body = await item.method.call(inst, response, next);
      });
    });
    this.app.use(router.routes()).use(router.allowedMethods());
  }

  protected async createDataSource(options: DataSourceOptions, typeormName?: string): Promise<DataSource> {
    const dataSource = new DataSource(options);
    await dataSource
      .initialize()
      .then(() => {
        // console.log("Data Source has been initialized!")
        console.log("数据库连接成功!");
      })
      .catch((err) => {
        console.error(" 数据库连接报错Error during Data Source initialization:", err);
      });
    this.container.bindDataSource(dataSource);
    return dataSource;
  }

  server() {
    return this.app;
  }
}
